package com.ecole.mines.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

import com.ecole.mines.model.Eleve;
import com.ecole.mines.model.Signature;

public class ParserJSONEleve extends
		AsyncTask<String, Integer, ArrayList<Eleve>>
{
	private OnTaskCompleted listener;
	private static final String URL_SERVEUR="http://91.121.167.164/Emargement-Web/web/app_dev.php";
	
    // constructor
    public ParserJSONEleve() {
    }
    
	public ParserJSONEleve(OnTaskCompleted listener)
	{
        this.listener=listener;
    }
    
	@Override
	protected ArrayList<Eleve> doInBackground(String... params) 
	{
		System.out.println("Params 1 "+params[1]);
		JSONArray jArray=getJSONFromUrl(params[0],params[1]);
		if(jArray!=null && jArray.length()>0)
		{
			return this.parserJSON(jArray);
		}
		else
			return new ArrayList<Eleve>();
	}
	
	@Override
	protected void onPostExecute(ArrayList<Eleve> result) 
	{
		listener.onTaskCompletedPromo(result);
	}
    
	public JSONArray getJSONFromUrl(String url,String idGroupe) {

		InputStream is = null;
		JSONArray jArr = null;
		String json = "";

		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(URL_SERVEUR + url);
			//httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("idGroupe",idGroupe));
		    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse httpResponse = httpClient.execute(httpPost);
			
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "utf-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			jArr = new JSONArray(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
			jArr=null;
		}

		return jArr;
	}
    	
	
    public ArrayList<Eleve> parserJSON(JSONArray jsonArray)
    {
    	ArrayList<Eleve> listeEleves 	=new ArrayList<Eleve>();
    	for (int i = 0; i < jsonArray.length(); i++) {
    		Eleve eleve=new Eleve();
			JSONObject object=new JSONObject();
			JSONArray arrayCours=new JSONArray();
			try {
				object=(JSONObject)jsonArray.get(i);
				eleve.setId(object.optInt("id"));
				eleve.setNom(object.optString("lastname"));
				eleve.setPrenom(object.optString("firstname"));
				eleve.setHasSigned(false);
				eleve.setSignatures(new ArrayList<Signature>());
			} 
			catch (JSONException e) 
			{
				Log.e("PARSER",e.getMessage());
			}
			listeEleves.add(eleve);
		}
    	
    	return listeEleves;
    }
    
}
